package com.twd.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.ImmediateEventExecutor;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup group = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
            group.add(ctx.channel());
            // 新的连接
            for (Channel channel : group) {
                String message = ctx.channel().id().asShortText() + " 加入聊天室...";
                channel.writeAndFlush(new TextWebSocketFrame(message));
                channel.writeAndFlush(new TextWebSocketFrame(message));

            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
        System.out.println("============");
    }
    public static void main(String[] args) {
        HttpRequestHandler httpRequestHandler = new HttpRequestHandler();
        Class<HttpRequestHandler> httpRequestHandlerClass = HttpRequestHandler.class;
        Field[] declaredFields = httpRequestHandlerClass.getDeclaredFields();

        Map<Class<?>, Field[]> map=new HashMap<>();
        map.put(httpRequestHandlerClass,declaredFields);
        map.put(TextWebSocketFrameHandler.class,null);

        System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
        for (int i = 0; i < 100000000; i++) {
            if(map.containsKey(httpRequestHandlerClass)){
                map.get(httpRequestHandlerClass);
            }else{
                httpRequestHandlerClass.getDeclaredFields();
            }
        }

        System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));


    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 客户端发送的文本
        String text = msg.text();
        // 构建Message
        String message = ctx.channel().id().asShortText()+text;

        // 广播所有客户端
        for (Channel channel : group) {
            channel.writeAndFlush(new TextWebSocketFrame(message));
        }
    }
}
